package com.tandan.mqttdemo0730.controller;

import com.tandan.mqttdemo0730.scheduler.MqttDataScheduler;
import com.tandan.mqttdemo0730.service.MqttService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * MQTT控制器 - 提供REST接口用于手动操作
 */
@RestController
@RequestMapping("/api/mqtt")
public class MqttController {

    @Autowired
    private MqttService mqttService;

    @Autowired
    private MqttDataScheduler mqttDataScheduler;

    /**
     * 检查MQTT连接状态
     */
    @GetMapping("/status")
    public Map<String, Object> getStatus() {
        Map<String, Object> result = new HashMap<>();
        result.put("connected", mqttService.isConnected());
        result.put("messageCount", mqttDataScheduler.getMessageCount());
        return result;
    }

    /**
     * 手动发送一条传感器数据
     */
    @PostMapping("/send/sensor")
    public Map<String, Object> sendSensorData() {
        Map<String, Object> result = new HashMap<>();
        try {
            mqttService.publishSimulatedData();
            result.put("success", true);
            result.put("message", "传感器数据发送成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "发送失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 手动发送自定义消息
     */
    @PostMapping("/send/custom")
    public Map<String, Object> sendCustomMessage(@RequestParam String topic, @RequestBody String message) {
        Map<String, Object> result = new HashMap<>();
        try {
            mqttService.publish(topic, message);
            result.put("success", true);
            result.put("message", "自定义消息发送成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "发送失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 手动发送JSON对象消息
     */
    @PostMapping("/send/json")
    public Map<String, Object> sendJsonMessage(@RequestParam String topic, @RequestBody Map<String, Object> data) {
        Map<String, Object> result = new HashMap<>();
        try {
            mqttService.publishObject(topic, data);
            result.put("success", true);
            result.put("message", "JSON消息发送成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "发送失败: " + e.getMessage());
        }
        return result;
    }
}